package com.mqtt;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class MqttUtil {
	
	public static Connection getConnection(MqttConfig mqttConfig) throws Exception{
		// 1.创建连接工厂对象（ConnectionFactory）
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
        		mqttConfig.getUsername(),mqttConfig.getPassword(),mqttConfig.getServerUrl());
        // 2.创建连接对象（Connection）
        Connection connection = connectionFactory.createConnection();
        // 3.启动连接
        connection.start();
        return connection;
	}
	
	public static void send(Connection connection,String topic,String message) throws Exception{
		if(connection==null){
			return;
		}
		// 创建session会话，第一参数表示启用事务处理，第二个参数表示启动哪种应答模式，这里启用的是自动应答
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topic);
        MessageProducer producer = session.createProducer(destination);
        TextMessage textMessage = session.createTextMessage(message);
        producer.send(destination, textMessage);
	}
	
	public static void recv(Connection connection,String topic,MessageListener messageListener) throws Exception{
		if(connection==null){
			return;
		}
		//创建session
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Destination destination = session.createTopic(topic);
        MessageConsumer messageConsumer = session.createConsumer(destination);
        messageConsumer.setMessageListener(messageListener);
	}
}
